package com.neusoft.elm.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.neusoft.elm.dao.BusinessDao;
import com.neusoft.elm.dao.CartDao;
import com.neusoft.elm.dao.DeliveryAddressDao;
import com.neusoft.elm.dao.OrdersDao;
import com.neusoft.elm.dao.OrderDetailetDao;
import com.neusoft.elm.dao.impl.BusinessDaoImpl;
import com.neusoft.elm.dao.impl.CartDaoImpl;
import com.neusoft.elm.dao.impl.DeliveryAddressDaoImpl;
import com.neusoft.elm.dao.impl.OrdersDaoImpl;
import com.neusoft.elm.dao.impl.OrderDetailetDaoImpl;
import com.neusoft.elm.po.Business;
import com.neusoft.elm.po.Cart;
import com.neusoft.elm.po.DeliveryAddress;
import com.neusoft.elm.po.Orders;
import com.neusoft.elm.po.OrderDetailet;
import com.neusoft.elm.service.OrdersService;
import com.neusoft.elm.util.DBUtil;
import com.neusoft.elm.util.MoneyUtil;

public class OrdersServiceImpl implements OrdersService {

	/**
	 * 创建订单：接收当前用户、商家、配送地址，处理购物车商品，生成订单和订单详情，返回订单号
	 */
	@Override
	public int createOrders(String userId, Integer businessId, Integer daId) {
		int orderId = 0;
		BusinessDao businessDao = new BusinessDaoImpl();
		CartDao cartDao = new CartDaoImpl();
		OrdersDao ordersDao = new OrdersDaoImpl();
		OrderDetailetDao orderDetailetDao = new OrderDetailetDaoImpl();
		DeliveryAddressDao daDao = new DeliveryAddressDaoImpl();

		try {
			DBUtil.beginTransaction();

			// 1. 查询购物车信息
			Cart cart = new Cart();
			cart.setBusinessId(businessId);
			cart.setUserId(userId);
			List<Cart> cartList = cartDao.listCart(cart);

			// 2. 查询商家信息
			Business business = businessDao.getBusinessById(businessId);

			// 3. 查询配送地址信息
			DeliveryAddress deliveryAddress = daDao.getDeliveryAddressById(daId);

			// 4. 使用MoneyUtil精确计算订单总额
			double ordersTotal = 0.0;
			for (Cart c : cartList) {
				double itemTotal = MoneyUtil.multiply(c.getFood().getFoodPrice(), c.getQuantity());
				ordersTotal = MoneyUtil.add(ordersTotal, itemTotal);
			}

			// 添加配送费
			ordersTotal = MoneyUtil.add(ordersTotal, business.getDeliveryPrice());

			// 5. 创建订单，保存历史信息
			Orders orders = new Orders();
			orders.setUserId(userId);
			orders.setBusinessId(businessId);
			orders.setOrderTotal(ordersTotal);
			orders.setDaId(daId);
			// 保存下单时的商家信息（历史快照）
			orders.setBusinessName(business.getBusinessName());
			orders.setDeliveryPrice(business.getDeliveryPrice());
			// 保存下单时的配送地址（历史快照）
			orders.setDeliveryAddress(deliveryAddress.getAddress());

			orderId = ordersDao.saveOrders(orders);

			// 6. 创建订单详情，保存商品历史信息
			List<OrderDetailet> orderDetailetList = new ArrayList<>();
			for (Cart c : cartList) {
				OrderDetailet od = new OrderDetailet();
				od.setOrderId(orderId);
				od.setFoodId(c.getFoodId());
				od.setQuantity(c.getQuantity());
				// 保存下单时的商品信息（历史快照）
				od.setFoodName(c.getFood().getFoodName());
				od.setFoodPrice(c.getFood().getFoodPrice());
				orderDetailetList.add(od);
			}

			// 7. 批量插入订单详情
			orderDetailetDao.saveOrderDetailetBatch(orderDetailetList);

			// 8. 清空购物车
			cartDao.removeCart(cart);

			DBUtil.commitTransaction();
		} catch (Exception e) {
			orderId = 0;
			try {
				DBUtil.rollbackTransaction();
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		} finally {
			DBUtil.close();
		}
		return orderId;
	}

	@Override
	public Orders getOrdersById(Integer orderId) {
		Orders orders = null;
		OrdersDao dao = new OrdersDaoImpl();
		try {
			DBUtil.getConnection();
			orders = dao.getOrdersById(orderId);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.close();
		}
		return orders;
	}

	@Override
	public List<Orders> listOrdersByUserId(String userId) {
		List<Orders> list = new ArrayList<>();
		OrdersDao ordersDao = new OrdersDaoImpl();
		OrderDetailetDao orderDetailetDao = new OrderDetailetDaoImpl();
		try {
			DBUtil.beginTransaction();
			// 先查询当前用户所有订单
			list = ordersDao.listOrdersByUserId(userId);
			for (Orders o : list) {
				// 再查询每个订单的详情
				List<OrderDetailet> odList = orderDetailetDao.listOrderDetailetByOrderId(o.getOrderId());
				o.setList(odList);
			}
			DBUtil.commitTransaction();
		} catch (Exception e) {
			try {
				DBUtil.rollbackTransaction();
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		} finally {
			DBUtil.close();
		}
		return list;
	}

	/**
	 * 计算订单项小计的辅助方法
	 * 
	 * @param price    单价
	 * @param quantity 数量
	 * @return 小计金额
	 */
	public static double calculateItemTotal(double price, int quantity) {
		return MoneyUtil.multiply(price, quantity);
	}

	/**
	 * 计算订单总金额的辅助方法
	 * 
	 * @param itemTotals 各项金额
	 * @return 总金额
	 */
	public static double calculateOrderTotal(double... itemTotals) {
		return MoneyUtil.sum(itemTotals);
	}
}